import {getCookie, verifyEmail, bindCaptchaBtn} from './utils.js'


function bindRegisterBtn() {
    $("#register-btn").click(function (event) {
        event.preventDefault();
        let email = $("#email").val();
        let captcha = $("#captcha").val();
        let password = $("#password").val();
        let password2 = $("#password2").val();
        let username = $("#username").val();
        const csrftoken = getCookie('csrftoken'); // 获取 CSRF Token

        if (!verifyEmail(email)) {
            return;
        } else if (!captcha || !password || !password2 || !username) {
            alert("请输入完整信息!");
            return;
        } else if (password !== password2) {
            alert("两次输入的密码不一致!");
            return;
        }

        $.ajax({
            url: "/auth/register/",
            method: 'POST',
            headers: {
                "X-CSRFToken": csrftoken // 添加 CSRF Token 到请求头
            },
            data: {
                email: email,
                captcha: captcha,
                password: password,
                password2: password2,
                username: username
            },
            success: function (data) {
                if (data.code === 200) {
                    alert('注册成功');
                    window.location.href = "/auth/login";
                } else {
                    alert(`Error:${data.message}!`);
                }
            },
            error: function (xhr, status, error) {
                alert(`请求失败: ${error}`);
            }
        })
    })
}


$(function () {
    bindCaptchaBtn();
    bindRegisterBtn();
})